﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DreamBuilder.UI.UserControls.DataAccess;
using DreamBuilder.UI.UserControls.DataAccess.Services;
using DreamBuilder.Core.Container;
using System.Data;
using Microsoft.Practices.Unity;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections;
using DreamBuilder.Common;

namespace DreamBuilder.UI.UserControls
{
    public partial class AttachmentManager1 : ControlBase
    {
        public string ObjectID
        {
            set
            {
                ViewState["ObjectID"] = value;
            }
            get
            {
                if (ViewState["ObjectID"] == null)
                {
                    return String.Empty;
                }
                return (string)ViewState["ObjectID"];
            }
        }
        private Hashtable htFileNames; 
        public Hashtable FileNames
        {
            get
            {

                return htFileNames;
            }
        }

        /// <summary>
        /// 附件类型//ADD By YSP 2011-07-25
        /// </summary>
        public string FunctionID
        {
            set
            {
                ViewState["FunctionID"] = value;
            }
            get
            {
                if (ViewState["FunctionID"] == null)
                {
                    return String.Empty;
                }
                return (string)ViewState["FunctionID"];
            }
        }

        public string ObjectTableName
        {
            set
            {
                ViewState["ObjectTableName"] = value;
            }
            get
            {
                if (ViewState["ObjectTableName"] == null)
                {
                    return String.Empty;
                }
                return (string)ViewState["ObjectTableName"];
            }
        }

        public string AttachmentDBHelperString
        {
            get
            {
                if (ViewState["DBHelperString"] == null)
                {

                    EPPage page = HttpContext.Current.Handler as EPPage;
                    if (page != null && !string.IsNullOrEmpty(page.DBHelpName))
                    {
                        return page.DBHelpName;
                    }
                }
                return ViewState["DBHelperString"].ToString();
            }
            set
            {
                ViewState["DBHelperString"] = value;
            }
        }


        [Dependency]
        public AttachmentDAL attachmentDAL
        {
            get
            {
                AttachmentDAL attachmentDAL = UContainer.Resolve<AttachmentDAL>();
                attachmentDAL.AttachmentDBHelperString = AttachmentDBHelperString;
                return attachmentDAL;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //注册文件
            RegistFiles();
            //生成swfupload路径
            CreateApplicationPath();
            //SetMyViewStateID();
            InitJsCultureInfo();
            //设置标题多语
            SetTitleText();

            AttachmentUploadFileInfo uf = new AttachmentUploadFileInfo();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AttachmentUploadFileInfo));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms, uf);
            this.Bind();

            if (!IsPostBack)
            {
                this.hidAttachmentAddList1.Value = string.Empty;
                this.hidAttachmentDeleteList1.Value = string.Empty;
            }

            ShowAttachments();
        }

        private void SetTitleText()
        {
        }


        private void ShowAttachments()
        {
            DataTable dt = attachmentDAL.GetAttachmentList(this.ObjectID, this.ObjectTableName, this.hidAttachmentAddList1.Value, this.hidAttachmentDeleteList1.Value, this.FunctionID);
            if (dt != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<script>");
                foreach (DataRow dr in dt.Rows)
                {
                    sb.Append("AddAttachment1('" + dr["AttachmentID"].ToString() + "','" + dr["AttachmentName"].ToString() + "','" + dr["AttachmentSize"].ToString() + "','" + Convert.ToDateTime(dr["UploadTime"]).ToString("yyyy-MM-dd HH:mm:ss") + "','" + this.hidAttachmentDeleteList1.ClientID + "','" + this.AttachmentTable1.ClientID + "','" + AttachmentDBHelperString + "');");
                }
                sb.Append("</script>");
                Page.ClientScript.RegisterStartupScript(this.GetType(), "attachmentDataList1" + this.FunctionID, sb.ToString());
            }
        }

        private void InitJsCultureInfo()
        {
            base.ControlPath = "UserControls/AttachmentManager1";
            StringBuilder sb = new StringBuilder();
            sb.Append("<script>");
            sb.Append(" var resBtnSelectFile = '" + GetString("BtnSelectFile") + "'; \n");
            sb.Append(" var resAlertZeroFile = '" + GetString("AlertZeroFile") + "'; \n");
            sb.Append(" var resAlertBigFile = '" + GetString("AlertBigFile") + "'; \n");
            sb.Append(" var resUploadSuccess = '" + GetString("UploadSuccess") + "'; \n");
            sb.Append(" var resUploadPercentage = '" + GetString("UploadPercentage") + "'; \n");
            sb.Append(" var currentCulture = '" + base.GetCurrentCulture + "'; \n");
            sb.Append("</script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "attachmentResInfo1", sb.ToString());
        }

       private void Bind()
        {
            TableRow trheader = new TableRow();
            trheader.CssClass = "AT-Header";
            this.AttachmentTable1.Rows.Add(trheader);

            //文件名列
            TableCell tcFileName = new TableCell();
            tcFileName.Text = "文件名";
            tcFileName.CssClass = "AT-Header-FileName";
            trheader.Cells.Add(tcFileName);
            
            //文件大小列
            TableCell tcFileSize = new TableCell();
            tcFileSize.Text = "文件大小";
            tcFileSize.CssClass = "AT-Header-FileSize";
            trheader.Cells.Add(tcFileSize);
            //文件上传日期列
            TableCell tcFileDate = new TableCell();
            tcFileDate.Text = "上传时间";
            tcFileDate.CssClass = "AT-Header-FileDate";
            trheader.Cells.Add(tcFileDate);

            //文件上传状态
            TableCell tcFileUploadStatus = new TableCell();
            tcFileUploadStatus.Text = "上传状态";
            tcFileUploadStatus.CssClass = "AT-Header-FileUploadStatus";
            trheader.Cells.Add(tcFileUploadStatus);
      
        }



        /// <summary>
        /// 生成swfupload.swf路径
        /// </summary>
        private void CreateApplicationPath()
        {
            string path = "<script>var applicationPath ='" + System.Web.HttpContext.Current.Request.ApplicationPath + "';</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "applicationPath1", path);
        }

        /// <summary>
        /// 注册文件
        /// </summary>
        private void RegistFiles()
        {
            //注册脚本文件
            string swfupload = System.Web.HttpContext.Current.Request.ApplicationPath + "/Javascript/swfupload1.js";
            string handlers = System.Web.HttpContext.Current.Request.ApplicationPath + "/Javascript/Attachment1.js";
            string json2 = System.Web.HttpContext.Current.Request.ApplicationPath + "/Javascript/json2.js";
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "swfupload", swfupload);
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "handlers1", handlers);
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "json2", json2);
            //注册css样式文件
            string cssSWFUpload = "<link href=\"" + System.Web.HttpContext.Current.Request.ApplicationPath + "/Styles/UCAttachment1.css\" rel=\"stylesheet\" type=\"text/css\" />";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "cssSWFUpload1", cssSWFUpload);
        }

        public DataTable GetSaveDataTable(string ObjectID, string ObjectTableName)
        {
            DataTable dt = this.attachmentDAL.GetSaveDataTable(ObjectID, ObjectTableName, this.hidAttachmentAddList1.Value, this.hidAttachmentDeleteList1.Value);
            return dt;
        }


        /// <summary>
        /// 获取与SWFUpload控件组合后的控件Id
        /// </summary>
        /// <param name="id">副Id</param>
        /// <returns></returns>
        protected string GetControlId(string id)
        {
            return string.Format("{0}_{1}", this.ID, id.Trim());
        }
    }
}